import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/login/index.vue'
import Layout from '../views/layout/index.vue'
import Employee from '../views/employee/index.vue'
import Product from '../views/product/index.vue'
import StockIn from '../views/stock-in/index.vue'
import StockOut from '../views/stock-out/index.vue'
import StockCheck from '../views/stock-check/index.vue'
import StockTransfer from '../views/stock-transfer/index.vue'
import StockRecord from '../views/stock-record/index.vue'
import StockWarning from '../views/stock-warning/index.vue'
import Customer from '../views/customer/index.vue'
import Dashboard from '../views/dashboard/index.vue'
import Supplier from '../views/supplier/index.vue'
import StockWarningStatistics from '../views/stock-warning/statistics.vue' // 引入新组件


const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表盘' }
      },
      {
        path: 'employee',
        name: 'Employee',
        component: Employee,
        meta: { title: '员工管理' }
      },
      {
        path: 'product',
        name: 'Product',
        component: Product,
        meta: { title: '产品管理' }
      },
      {
        path: 'customer',
        name: 'Customer',
        component: Customer,
        meta: { title: '客户管理' }
      },
      {
        path: 'supplier',
        name: 'Supplier',
        component: Supplier,
        meta: { title: '供应商管理' }
      },
      {
        path: 'stock-in',
        name: 'StockIn',
        component: StockIn,
        meta: { title: '入库管理' }
      },
      {
        path: 'stock-out',
        name: 'StockOut',
        component: StockOut,
        meta: { title: '出库管理' }
      },
      {
        path: 'stock-check',
        name: 'StockCheck',
        component: StockCheck,
        meta: { title: '盘点管理' }
      },
      {
        path: 'stock-transfer',
        name: 'StockTransfer',
        component: StockTransfer,
        meta: { title: '调拨管理' }
      },
      {
        path: 'stock-record',
        name: 'StockRecord',
        component: StockRecord,
        meta: { title: '库存记录' }
      },
      {
        path: 'stock-warning',
        name: 'StockWarning',
        component: StockWarning,
        meta: { title: '库存预警' }
      },
      {
        path: 'stock-warning/statistics',
        name: 'StockWarningStatistics',
        component: StockWarningStatistics // 注册新路由
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const publicPages = ['/login']
  const authRequired = !publicPages.includes(to.path)
  const token = localStorage.getItem('token')

  if (authRequired && !token) {
    next('/login')
  } else {
    next()
  }
})

export default router
